<!-- scripts for initializing and cofiguring the calendar -->
<script type='text/javascript' src='<{$event_script_url}>fullcalendar.min.js'></script>
<{if $calendars || $calendar}>
<script type='text/javascript' src='<{$event_script_url}>gcal.js'></script>
<{/if}>
<script type='text/javascript' src='<{$event_script_url}>jquery.qtip.min.js'></script>
<{if $cat_submit}>
<script type='text/javascript' src='<{$event_script_url}>jquery-ui-timepicker-addon.js'></script>
<{/if}>
<script type='text/javascript'>
	$(document).ready(function() {
		var date = new Date();
		var d = date.getDate();
		var m = date.getMonth();
		var y = date.getFullYear();
		var h = date.getHours();
		var i = date.getMinutes();
		var lastView;
		var isResizingEvent = false;
		<{if $use_checkboxes}>
			document.forms.event_catselect.reset();
		<{/if}>
		var calendar = $('#calendar').fullCalendar({
			defaultView: '<{$default_view}>',
			aspectRatio: 1.35,
			header: {
				left: 'prev,next today',
				center: 'title',
				right: 'month,agendaWeek,agendaDay'
			},
			weekNumbers: <{$display_weeknumber}>,
			slotMinutes: <{$agenda_slot}>,
            firstHour: <{$agenda_start}>,
			axisFormat: 'HH:mm',
			timeFormat: {
			    agenda: 'HH:mm'
			},
			dragOpacity: {
			    agenda: .5
			},
			minTime: <{$agenda_min}>,
			maxTime: <{$agenda_max}>,
			dayNumberClickable: true,
			dayClick: function(date, allDay, jsEvent, view) {
				if(view.name != 'month')
					return;
				lastView = view.name;
    			$('#calendar').fullCalendar('changeView', 'agendaDay')
    				.fullCalendar('gotoDate', date);
			},
			eventClick: function(event, jsEvent, view) {clickEvent(event, jsEvent, view)},
			isRTL: <{$event_rtl}>,
			firstDay: <{$first_day}>,
			weekends: <{$display_weekend}>,
			monthNames: ['<{$smarty.const._CO_EVENT_JANUARY}>','<{$smarty.const._CO_EVENT_FEBRUARY}>','<{$smarty.const._CO_EVENT_MARCH}>','<{$smarty.const._CO_EVENT_APRIL}>','<{$smarty.const._CO_EVENT_MAY}>',
							'<{$smarty.const._CO_EVENT_JUNE}>','<{$smarty.const._CO_EVENT_JULY}>','<{$smarty.const._CO_EVENT_AUGUST}>','<{$smarty.const._CO_EVENT_SEPTEMBER}>','<{$smarty.const._CO_EVENT_OCTOBER}>',
							'<{$smarty.const._CO_EVENT_NOVEMBER}>','<{$smarty.const._CO_EVENT_DECEMBER}>'],
			monthNamesShort: ['<{$smarty.const._CO_EVENT_JAN}>','<{$smarty.const._CO_EVENT_FEB}>','<{$smarty.const._CO_EVENT_MAR}>','<{$smarty.const._CO_EVENT_APR}>','<{$smarty.const._CO_EVENT_MAI}>','<{$smarty.const._CO_EVENT_JUN}>',
								 '<{$smarty.const._CO_EVENT_JUL}>','<{$smarty.const._CO_EVENT_AUG}>','<{$smarty.const._CO_EVENT_SEP}>','<{$smarty.const._CO_EVENT_OCT}>','<{$smarty.const._CO_EVENT_NOV}>','<{$smarty.const._CO_EVENT_DEC}>'],
			dayNames: ['<{$smarty.const._CO_EVENT_SUNDAY}>','<{$smarty.const._CO_EVENT_MONDAY}>','<{$smarty.const._CO_EVENT_TUESDAY}>','<{$smarty.const._CO_EVENT_WEDNESDAY}>','<{$smarty.const._CO_EVENT_THURSDAY}>',
							 '<{$smarty.const._CO_EVENT_FRIDAY}>','<{$smarty.const._CO_EVENT_SATURDAY}>'],
			dayNamesShort: ['<{$smarty.const._CO_EVENT_SU}>','<{$smarty.const._CO_EVENT_MO}>','<{$smarty.const._CO_EVENT_TU}>','<{$smarty.const._CO_EVENT_WE}>','<{$smarty.const._CO_EVENT_TH}>',
								'<{$smarty.const._CO_EVENT_FR}>','<{$smarty.const._CO_EVENT_SA}>'],
			buttonText: {
				prev: '&nbsp;&#9668;&nbsp;',
				next: '&nbsp;&#9658;&nbsp;',
				prevYear: '&nbsp;&lt;&lt;&nbsp;',
				nextYear: '&nbsp;&gt;&gt;&nbsp;',
				today: '<{$smarty.const._CO_EVENT_TODAY}>',
				month: '<{$smarty.const._CO_EVENT_MONTH}>',
				week: '<{$smarty.const._CO_EVENT_WEEK}>',
				day: '<{$smarty.const._CO_EVENT_DAY}>'
			},
			titleFormat: {
				month: '<{$default_header_m}>',
				week: "<{$default_header_w}>",
				day: '<{$default_header_d}>'
			},
			columnFormat: {
				month: '<{$default_column_m}>',
				week: '<{$default_column_w}>',
				day: '<{$default_column_d}>'
			},
			timeFormat:{
				agenda: '<{$default_time_a}>',
				'': '<{$default_time}>'
			},
			allDayText: '<{$smarty.const._CO_EVENT_ALLDAY}>',
			theme: <{$use_theme}>,
			buttonIcons: {
				prev: 'circle-triangle-w',
				next: 'circle-triangle-e'
			},
			eventSources: [
				<{if $category}>
					{
						url: "<{$event_url}>feeds.php?cat=<{$category.id}><{if $icms_userid}>&uid=<{$icms_userid}><{/if}>",
						className: 'event_cal_<{$category.id}>',
						color: "<{$category.color}>",
						textColor: '<{$category.txtcolor}>',
						ignoreTimezone: false,
						currentTimezone: '<{$default_timezone}>'
					}
				<{elseif $calendar}>
					{
						url: "<{$calendar.url}>",
						className: 'google_cal_<{$calendar.id}>',
						color: "<{$calendar.color}>",
						textColor: '<{$calendar.txtcolor}>',
						currentTimezone: '<{$calendar.default_tz}>'
					}
				<{else}>
					<{foreach item=cat from=$categories name=category}>
						{
							url: "<{$event_url}>feeds.php?cat=<{$cat.id}><{if $icms_userid}>&uid=<{$icms_userid}><{/if}>",
							className: 'event_cal_<{$cat.id}>',
							color: "<{$cat.color}>",
							textColor: '<{$cat.txtcolor}>',
							ignoreTimezone: false,
							currentTimezone: '<{$default_timezone}>'
						}<{if !$smarty.foreach.category.last}>,<{/if}>
					<{/foreach}>
					<{if ($categories || $category) && $calendars}>,<{/if}>
					<{if $calendars}>
						<{foreach item=cal from=$calendars name=calendar}>
						{
							url: "<{$cal.url}>",
							className: 'google_cal_<{$cal.id}>',
							color: "<{$cal.color}>",
							textColor: '<{$cal.txtcolor}>',
							currentTimezone: '<{$cal.default_tz}>'
						}<{if !$smarty.foreach.calendar.last}>,<{/if}>
						<{/foreach}>
					<{/if}>
				<{/if}>
			],
			ignoreTimezone: false,
			eventRender: function(event, element) {
				element.attr("id", event.seo);
        		element.qtip({
		            content: {
		                title: { text: event.title },
		                text: (!event.allDay) ? '<span class="start">Start: </span>' + ($.fullCalendar.formatDate(event.start, 'HH:mm')) +
		                		'<br /><span class="End">End: </span>' + ($.fullCalendar.formatDate(event.end, 'HH:mm')) +
		                		'<br /><span class="dsc">Description: </span><p>' + event.description +
		                		'</p><br />' + event.approval : '<span class="start">Start: </span><{$smarty.const._CO_EVENT_ALLDAY}><br /><span class="dsc">Description: </span><p>' + event.description +
		                		'</p><br />' + event.approval
					},
					show: { solo: true },
		            style: {
		                width: 500,
		                padding: 5,
		                classes: 'qtip-dark qtip-rounded qtip-shadow',
		                tip: 'topLeft',
						textAlign:'left',
						tip:'bottomLeft',
		                classes: 'qtip-dark qtip-rounded qtip-shadow'
		            },
		            position: {
						target: 'mouse',
						my:'bottomLeft',
						adjust: {
							x: 0,  y: -5
						}
					}
		        });
    		},
    		viewDisplay: function(view) {
    			var timelineInterval;
				window.clearInterval(timelineInterval);
				timelineInterval = window.setInterval(setTimeline, 10000);
				try {
					setTimeline();
				} catch(err) { }
			},
			loading: function(isLoading, view) {
				//var view = $('#calendar').fullCalendar('getView');
				if(!isLoading) {
					$("#event_loading").hide();
					<{if $smarty.get.event}>
						if(view.name == "agendaDay") openEvent();
					<{/if}>
				} else {
					$("#event_loading").show();
				}
			},

    		<{if $cat_submit}>
	    		dropAccept: '*',
				selectable: true,
				selectHelper: true,
				editable: false,
				select: function(startDate, endDate, allDay) {
					var view = $('#calendar').fullCalendar('getView');
					if(view.name != "agendaWeek" && view.name != "agendaDay" )
						return;
					if(startDate < date && lastView != 'month') {
						$("#event_alert").html("<{$smarty.const._CO_EVENT_CANNOT_BOOK_PAST}>");
						$("#event_alert").dialog("open");
						calendar.fullCalendar( 'unselect' );
					} else {
						if(lastView != 'month')
						var title = prompt('<{$smarty.const._MD_EVENT_TITLE}>');
						title = title;
						start = $.fullCalendar.formatDate( startDate, "yyyy/MM/dd HH:mm");
						end = $.fullCalendar.formatDate( endDate, "yyyy/MM/dd HH:mm");
						$("#event_startdate").val(start);
						$("#event_enddate").val(end);
						$("#event_name").val(title);
						$("#event_allday").val(allDay);
						$("#event_id, #event_cid, #event_dsc_tarea, #event_phone, #event_street, #event_city, #event_can_joint").val('');
						$("#mid_event_url, #caption_event_url, #desc_event_url, #url_event_url, #target_event_url").val('');
						$("#event_zip, #event_joiners").val();
						if(title) $("#submit_form").dialog("open");
						lastView = view.name;
					}
				},
				eventResizeStart: function () { isResizingEvent = true; },
				eventResizeStop: function () { isResizingEvent = false; },
				eventResize: function( event, dayDelta, minuteDelta, revertFunc, jsEvent, view ) {
					if(view.name == "month") {
						revertFunc();
					}
					$("#event_alert").html("<{$smarty.const._MD_EVENT_SURE_RESIZE}>");
					$("#event_alert").dialog({
						buttons:
							{
								"<{$smarty.const._CLOSE}>": function() {
									$(this).dialog("close");
									$(this).dialog("empty");
									revertFunc();
								},
							Ok: function() {
								$.ajax({
									url: "<{$event_url}>submit.php",
									type: "POST",
									data: { event_cid: event.cid, event_id: event.id, day_diff: dayDelta, min_diff: minuteDelta, op: "resizeevent"},
									dataType: "json",
									success: function(response) {
												if(response.status === "success") {
													$('#calendar').fullCalendar('refetchEvents');
													$("#error_messages").html(response.message);
												} else if(response.status === "error") {
													$("#error_messages").html("<{$smarty.const._MD_EVENT_FAILURE}>: " + response.message);
													revertFunc();
												}
									}
								});
								$(this).dialog( "close" );
								$(this).dialog("empty");
							}}
					});
					$("#event_alert").dialog("open");
				},
				eventDrop: function(event,dayDelta,minuteDelta,allDay,revertFunc) {
					$("#event_alert").html("<{$smarty.const._MD_EVENT_SURE_DROP}>");
					$("#event_alert").dialog({
						buttons:
							{
								"<{$smarty.const._CLOSE}>": function() {
									$(this).dialog("close");
									$(this).dialog("empty");
									revertFunc();
								},
							Ok: function() {
								$.ajax({
									url: "<{$event_url}>submit.php",
									type: "POST",
									data: { event_cid: event.cid, event_id: event.id, day_diff: dayDelta, min_diff: minuteDelta, event_allday: allDay, op: "dropevent"},
									dataType: "json",
									success: function(response) {
												if(response.status === "success") {
													$('#calendar').fullCalendar('refetchEvents');
													$("#error_messages").html(response.message);
												} else if(response.status === "error") {
													$("#error_messages").html("<{$smarty.const._MD_EVENT_FAILURE}>: " + response.message);
													revertFunc();
												} else {
													$("#error_messages").html("<{$smarty.const._MD_EVENT_FAILUREWENTWRONG}>: " + response.message);
													revertFunc();
												}
									}
								});
								$(this).dialog( "close" );
								$(this).dialog("empty");
							}}
					});
					$("#event_alert").dialog("open");
				}
			<{else}>
				selectable: false,
				selectHelper: false,
				editable: false,
				select: function(startDate, endDate, allDay) {
					calendar.fullCalendar('unselect');
				}
			<{/if}>
		});

		<{if $gotoDate }>
			/**
			 * jump to a submitted date
			 */
			$('#calendar').fullCalendar('changeView', 'agendaDay')
    				.fullCalendar('gotoDate', <{$gotoDate}>);
		<{/if}>

		/**
		 * adding new calendar button to submit events
		 */
		addCalButton("left", "<{$smarty.const._CO_EVENT_SUBMIT}>", "submit_button");

		<{if $cat_submit}>
			/**
			 * ui dialog for submitting events
			 */
			$( "#submit_form" ).dialog({
				title: "<{$smarty.const._MD_EVENT_ADDEVENT}>",
	        	autoOpen: false,
	        	height: 700,
	        	width: "90%",
	        	modal: true,
	        	buttons: {
		            "<{$smarty.const._MD_EVENT_CREATE_EVENT}>": function() {
		            	var dlg = $(this);
						$.ajax({
							url: $("#addevent").attr('action'),
							type: "POST",
							data: {event_id: $("#event_id").val(), event_name: $("#event_name").val(), event_startdate: $("#event_startdate").val(), event_enddate: $("#event_enddate").val(), event_allday: $("#event_allday").val(),
									event_cid: $("#event_cid").val(), event_dsc: $("#event_dsc_tarea").val(), event_contact: $("#event_contact").val(), event_cemail: $("#event_cemail").val(),
									event_phone: $("#event_phone").val(), event_street: $("#event_street").val(), event_city: $("#event_city").val(), event_zip: $("#event_zip").val(),
									event_public: $('input:radio[name=event_public]:checked').val(), mid_event_url: $("#mid_event_url").val(), caption_event_url: $("#caption_event_url").val(),
									desc_event_url: $("#desc_event_url").val(), url_event_url: $("#url_event_url").val(), target_event_url: $("#target_event_url").val(),
									event_can_joint: $('#event_can_joint').val(), event_joiners: $("#event_joiners").val(), op: $("#op").val()
								},
							dataType: "json",
							success: function(response) {
										if(response.status === "success") {
											dlg.dialog("close");
											$('#calendar').fullCalendar('refetchEvents');
											$('#form_message').dialog('open');
											document.forms.addevent.reset();
										} else if(response.status === "error") {
											$("#form_error").html("<{$smarty.const._MD_EVENT_FAILURE}>: " + response.message);
										}
							},
						});
					},
					"<{$smarty.const._CANCEL}>" : function() {
						$(this).dialog("close");
					}
				},
				Cancel: function() {
					$(this).dialog( "close" );
				}
			});

		    $("#event_startdate, #event_enddate").datetimepicker({
				isRTL: <{$event_rtl}>,
				monthNames: ['<{$smarty.const._CO_EVENT_JANUARY}>','<{$smarty.const._CO_EVENT_FEBRUARY}>','<{$smarty.const._CO_EVENT_MARCH}>','<{$smarty.const._CO_EVENT_APRIL}>','<{$smarty.const._CO_EVENT_MAY}>',
								'<{$smarty.const._CO_EVENT_JUNE}>','<{$smarty.const._CO_EVENT_JULY}>','<{$smarty.const._CO_EVENT_AUGUST}>','<{$smarty.const._CO_EVENT_SEPTEMBER}>','<{$smarty.const._CO_EVENT_OCTOBER}>',
								'<{$smarty.const._CO_EVENT_NOVEMBER}>','<{$smarty.const._CO_EVENT_DECEMBER}>'],
				monthNamesShort: ['<{$smarty.const._CO_EVENT_JAN}>','<{$smarty.const._CO_EVENT_FEB}>','<{$smarty.const._CO_EVENT_MAR}>','<{$smarty.const._CO_EVENT_APR}>','<{$smarty.const._CO_EVENT_MAI}>','<{$smarty.const._CO_EVENT_JUN}>',
									 '<{$smarty.const._CO_EVENT_JUL}>','<{$smarty.const._CO_EVENT_AUG}>','<{$smarty.const._CO_EVENT_SEP}>','<{$smarty.const._CO_EVENT_OCT}>','<{$smarty.const._CO_EVENT_NOV}>','<{$smarty.const._CO_EVENT_DEC}>'],
				dayNames: ['<{$smarty.const._CO_EVENT_SUNDAY}>','<{$smarty.const._CO_EVENT_MONDAY}>','<{$smarty.const._CO_EVENT_TUESDAY}>','<{$smarty.const._CO_EVENT_WEDNESDAY}>','<{$smarty.const._CO_EVENT_THURSDAY}>',
								 '<{$smarty.const._CO_EVENT_FRIDAY}>','<{$smarty.const._CO_EVENT_SATURDAY}>'],
				dayNamesMin: ['<{$smarty.const._CO_EVENT_SU}>','<{$smarty.const._CO_EVENT_MO}>','<{$smarty.const._CO_EVENT_TU}>','<{$smarty.const._CO_EVENT_WE}>','<{$smarty.const._CO_EVENT_TH}>',
									'<{$smarty.const._CO_EVENT_FR}>','<{$smarty.const._CO_EVENT_SA}>'],
				changeMonth: true,
				changeYear: true,
				dateFormat: "yy/mm/dd"
				//, timeFormat: "HH:mm",
			})

			$("#event_startdate").datetimepicker({
				defaultDate: $("#event_startdate").datetimepicker('getDate'),
				onClose: function(dateText, inst) {
					var eventStartDate = $("#event_startdate").datetimepicker("getDate");
					var eventEndDate = $("#event_enddate").datetimepicker("getDate");
					if ($("#event_enddate").val() != "") {
						if (eventStartDate > eventEndDate)
							$("#event_enddate").datetimepicker("setDate", eventStartDate);
					} else {
						$("#event_enddate").val(dateText);
					}
				},
				onSelect: function (selectedDateTime){
					var eventStartDate = $("#event_startdate").datetimepicker("getDate");
					var eventEndDate = $("#event_enddate").datetimepicker("getDate");
					if (eventStartDate > eventEndDate)
					$("#event_enddate").datetimepicker("option", "minDateTime", $("#event_startdate").datetimepicker("getDate") );
				}
			});

			$("#event_enddate").datetimepicker({
				defaultDate: $("#event_enddate").datetimepicker('getDate'),
				onClose: function(dateText, inst) {
						var eventStartDate = $("#event_startdate").datetimepicker("getDate");
						var eventEndDate = $("#event_enddate").datetimepicker("getDate");
						if ($("#event_startdate").val() != "") {
							if (eventStartDate > eventEndDate)
								$("#event_startdate").datetimepicker("setDate", eventEndDate);
						} else {
							$("#event_startdate").val(dateText);
						}
				},
				onSelect: function (selectedDateTime){
						var eventStartDate = $("#event_startdate").datetimepicker("getDate");
						var eventEndDate = $("#event_enddate").datetimepicker("getDate");
						if (eventStartDate > eventEndDate)
						$("#event_startdate").datetimepicker("setDate", eventStartDate);
				}
			});
			/**
			 * initializing submit button for submitting events
			 */
	    	$("#submit_button").click(function () {
	    		var title = prompt('<{$smarty.const._MD_EVENT_TITLE}>');
				title = title;
				$("#event_name").val(title);
	    		$("#submit_form").dialog("open")
	    	});
	    <{elseif !$cat_submit && !$icms_isUser}>
	    	$("#submit_button").click(function () {
	    		$("#event_alert").html("<{$smarty.const._MD_EVENT_REGISTER}>");
	    		$("#event_alert").dialog({
	    			buttons:
							{
								"<{$smarty.const._CLOSE}>": function() {
									$(this).dialog("close");
									$(this).dialog("empty");
									return false;
								},
							"<{$smarty.const._REGISTER}>": function() {
								window.location.href = "<{$icms_url}>/user.php";
							}}
				});
	    		$("#event_alert").dialog("open");
	    	});
	    <{else}>
	    	$("#event_alert").html("<{$smarty.const._NOPERM}>");
	    	$("#event_alert").dialog("open");
	    <{/if}>

	    /**
	     * initializing dialog on form success/redirect messages
	     */
		$("#form_message").dialog({
			title: "<{$smarty.const._MD_EVENT_THANKS}>",
			autoOpen: false,
			modal: true,
			hide: "explode",
			show: "slide",
			resizable: false,
			width: 300,
			height: "auto",
			buttons: {
				Ok: function() {
					$(this).dialog( "close" );
				}
			}
		});

		/**
		 * helps resizing calendars content in small themes
		 */
		$(window).resize(function() {
			if (isResizingEvent) { return; }
			var viewportHeight =  $(window).height()
			$('#calendar').fullCalendar('option', 'contentHeight',  $(window).height());
		});
		/**
		 * introducing dialog for cal events - basic
		 */
		$("#cal_event").dialog({
			autoOpen: false,
			modal: true,
			hide: "clip",
			show: "clip",
			resizable: false,
			width: 800,
			height: "auto"
		});

		/**
		 * replacement for old alert - makes div#event_alert a dialog box to return html content
		 */
		$("#event_alert").dialog({
			autoOpen: false,
			modal: true,
			hide: "clip",
			show: "clip",
			resizable: false,
			width: 800,
			height: "auto",
			buttons: {
				Ok: function() {
					$(this).dialog( "close" );
					$(this).dialog("empty");
				}
			}
		});

		/**
		 * make use of qtip for legend description
		 */
		$('.legend_item').each(function(){
			$(this).qtip({
				content: {
					text: $(this).next('div.event_popup').html(),
					title: $(this).attr('original-title')
				},
				style: {
					width:500,
					viewport: $(window),
					textAlign:'left',
					tip:'bottomLeft',
					classes: 'qtip-dark qtip-rounded qtip-shadow',
				},
				position:   {
					target: 'mouse',
					my:'bottomLeft',
					adjust: {
						x: 0,  y: -5
					}
				},
			});
		});
		/**
		 * submit function for cat legend
		 */
		$("#event_catselect").submit(function(e) {
			var form = $(this);
			e.preventDefault();
			$.ajax({
				url: form.attr('action'),
				type: "POST",
				data: {event_cats: $("input:checkbox[name=event_cats[]]").serializeArray()},
				dataType: "json",
				success: function(response) {
					if(response.status == "success") {
						$('#calendar').fullCalendar('removeEvents').fullCalendar('removeEventSources');
						$('#calendar').fullCalendar('lazyFetching', false);
						$.each(response.message, function(index, value) {
							$('#calendar').fullCalendar('addEventSource', {
								url: value.feed,
								className: value.classname,
								color: value.color,
								textColor: value.txtcolor,
								ignoreTimezone: false,
								currentTimezone: (value.timezone != "undefined") ? value.timezone : '<{$default_timezone}>'
							});
							$('#calendar').fullCalendar('rerenderEvents');
						});
						return false;
					}
				}
			});
			return false;
		});

		/**
		 * submitting  legend onChange checkboxes
		 */
		$('form#event_catselect input:checkbox').change(function(){
			$('#event_catselect').submit();
			return false;
		});

		/**
		 * additional functions
		 */
		/**
		 * adding a time line to agenda views (agendaDay and agendaWeek)
		 * @param curTime -> date object of the current time
		 * @return returns and refreshes a small time line in the current time slot all 5 minutes
		 */
		function setTimeline(calendar) {
			var curTime = new Date();
			if (curTime.getHours() == 0 && curTime.getMinutes() <= 5) {
				var todayElem = $(".fc-today");
				todayElem.removeClass("fc-today");
				todayElem.removeClass("fc-state-highlight");

				todayElem.next().addClass("fc-today");
				todayElem.next().addClass("fc-state-highlight");
			}

			var parentDiv = $(".fc-agenda-slots:visible").parent();
			var timeline = parentDiv.children(".timeline");
			if (timeline.length == 0) { //if timeline isn't there, add it
				timeline = $("<hr>").addClass("timeline");
				parentDiv.prepend(timeline);
			}

			var curCalView = $('#calendar').fullCalendar("getView");
			if (curCalView.visStart < curTime && curCalView.visEnd > curTime) {
				timeline.show();
			} else {
				timeline.hide();
			}

			var curSeconds = (curTime.getHours() * 60 * 60) + (curTime.getMinutes() * 60) + curTime.getSeconds();
			var percentOfDay = curSeconds / 86400; //24 * 60 * 60 = 86400, # of seconds in a day
			var topLoc = Math.floor(parentDiv.height() * percentOfDay);

			timeline.css("top", topLoc + "px");

			if (curCalView.name == "agendaWeek") {
				var dayCol = $(".fc-today:visible");
				if (dayCol.position() != null) {
					var left = dayCol.position().left + 1;
					var width = dayCol.width();
					timeline.css({
						left: left + "px",
						width: width + "px"
					});
				}
			}
		};
		/**
		 * adding new Buttons to cal header
		 */
		function addCalButton(where, text, id) {
			var my_button = '<span class="fc-header-space"></span>' +
							'<span id="' + id + '" class="cal-button">' + text +'</span>';
			$("td.fc-header-" + where).append(my_button);
			$("#" + id).button();
		}

		/**
		 * checks for seo input for opening an event
		 * @param seo - check if corrent seo is in available events
		 * @return return cklickEvent @ event seo Object
		 */
		function openEvent() {
			var eventSeo = "<{$smarty.get.event}>";
			var events = $('#calendar').fullCalendar('clientEvents',function(event) {return event.seo == eventSeo;});
			clickEvent(events[0]);
		};

		/**
		 * clickEvent fires a clicked event to dialog and opens dialog box for single Event view
		 * @param event -> single js-event Object to be opened
		 * @param jsEvent -> current jsEvent
		 * @param view -> contains the view object
		 * @return opening ui dialog and appends all event data to the template
		 */
		function clickEvent(event, jsEvent, view) {
				$('#calendar').fullCalendar('updateEvent', event);
				startDate = $.fullCalendar.formatDate(event.start, 'HH:mm');
				endDate = $.fullCalendar.formatDate(event.end, 'HH:mm');
				if(event.seo) {
					var printButton = "<a rel='external' target='blank' href='<{$event_url}>print.php?print=event&event=" + event.seo + "'><img id='event_print' src='<{$event_images_url}>print.png' alt='print' /></a>";
				} else {
					var printButton = "";
				}

				if(event.editable == true) {
					var buttons = "<span class='event_buttonbar'>" +
										"<img id='event_delete' src='<{$event_images_url}>delete.png' alt='delete' />" +
										"<img id='event_edit' src='<{$event_images_url}>edit.png' alt='edit' />" +
										"<img id='event_clone' src='<{$event_images_url}>clone.png' alt='edit' />" +
										printButton +
									"</span>";
				} else {
					var buttons = "<span class='event_buttonbar'>" + printButton + "</span>";
				}
				if(event.has_joint) {
					var join_link = "<div id='event_unjoin'><p><{$smarty.const._MD_EVENT_DISCHARGE}></p></div>"
				} else {
					if(event.can_joint) {
						var join_link = "<div id='event_join'><p><{$smarty.const._MD_EVENT_PARTICIPATE}></p></div>"
					} else {
						var join_link = "";
					}
				}
				$("div#show_event_dsc").html(event.description);
				$("div#cal_event").attr("data-id", event.id);

				var divClone = $("#event_date").clone();
				if(!event.allDay) {
					$("span#show_event_startdate").html(startDate);
					$("span#show_event_enddate").html(endDate);
					$("#event_date").show();
					$("#event_alldayevent").html("");
					$("#event_alldayevent").hide();

				} else {
					$("div#event_alldayevent").html("<{$smarty.const._CO_EVENT_ALLDAY}>");
					$("#event_alldayevent").show();
					$("#event_date").hide();
					$("span#show_event_startdate, span#show_event_enddate").html("");
				}
				<{if $can_comment}>
					if(event.cat === "google") {
						$("#event_commentform").hide();
						$("#event_comment_tarea").attr("disabled", "disabled");
						$("#submit_comment").attr("disabled", "disabled");
						$("#event_comment_container").hide();
						$("#event_comment_container").html("");
					} else {
						$("#event_commentform").show();
						$("#event_comment_tarea").removeAttr("disabled");
						$("#submit_comment").removeAttr("disabled");
						$("#event_comment_container").show();
					}
				<{/if}>
				if(event.comments !== "") {
					$("div#event_comment_container").html(event.comments);
					createToolTip();
				} else {
					$("div#event_comment_container").html("");
				}
				if(event.contact != false) {
					$("div#show_event_contact").html(event.contact);
					$("div#show_event_contact").parent("div").show();
				} else {
					$("div#show_event_contact").parent("div").hide();
				}
				if(event.street != "") {
					$("div#show_event_street").html(event.street);
					$("div#show_event_street").parent("div").show();
				} else {
					$("div#show_event_street").parent("div").hide();
				}
				if(event.city != "") {
					$("span#show_event_city").html(event.city);
					$("span#show_event_city").parent("div").parent("div").show();
				} else {
					$("span#show_event_city").html("");
					$("span#show_event_city").parent("div").parent("div").hide();
				}
				if(event.zip != 0) {
					$("span#show_event_zip").text(event.zip);
					$("span#show_event_zip").show();
				} else {
					$("span#show_event_zip").html("");
					$("span#show_event_zip").hide();
				}
				if(event.phone != false) {
					$("div#show_event_phone").html(event.phone);
					$("div#show_event_phone").parent("div").show();
				} else {
					$("div#show_event_phone").parent("div").hide();
				}
				if(event.cat !== "google") {
					$("div#show_event_cid").html(event.cat);
					$("div#show_event_cid").parent("div").show();
				} else {
					$("div#show_event_cid").html("");
					$("div#show_event_cid").parent("div").hide();
				}
				if(event.urllink != false) {
					$("div#show_event_url").html(event.urllink);
					$("div#show_event_url").parent("div").show();
				} else {
					$("div#show_event_url").html("");
					$("div#show_event_url").parent("div").hide();
				}
				if(event.approval) {
					$("div#awaiting_approval").html(event.approval);
					$("div#awaiting_approval").show();
				} else {
					$("div#awaiting_approval").html("");
					$("div#awaiting_approval").hide();
				}
				if(join_link != "") {
					$("div#event_joining").html(join_link);
					$("div#event_joining").show();
					$("div#event_join_info").html("<h3><{$smarty.const._MD_EVENT_PARTICIPATE_EVENT}></h3>"+ event.joiner_max);
					$("div#event_join_info").show();
				} else {
					$("div#event_joining").html("");
					$("div#event_joining").hide();
					$("div#event_join_info").html("");
					$("div#event_join_info").hide();
				}

				$("div#event_success").html("");

				if(event.joint_friends !== false) {
					$("div#joined_friends").html("<h3><{$smarty.const._MD_EVENT_JOINED_FRIENDS}></h3>"+ event.joint_friends);
					$("div#joined_friends").show();
				} else {
					$("div#joined_friends").html("");
					$("div#joined_friends").hide();
				}
				<{if $icms_isuser}>
					if(event.joiners != false) {
						$("div#joiners_list").html(event.joiners);
						$("div#joiners_list").parent("div").show();
					} else {
						$("div#joiners_list").html("");
						$("div#joiners_list").parent("div").hide();
					}
				<{else}>
					$("div#joiners_list").parent("div").hide();
				<{/if}>


				$("div#cal_event").dialog({
					title: buttons + event.title,
					buttons: [
						{
							text: "<{$smarty.const._CLOSE}>",
							click: function() {
								$(this).dialog("close");
								$(this).dialog("empty");
							}
						}
					]
				});
				$("div#cal_event").dialog("open");

				$('#event_delete').click(function(){
					var button = $(this);
					$("#event_alert").html("<{$smarty.const._MD_EVENT_SURE_DELETE}>");
					$("#event_alert").dialog({
						buttons:
							{
								"<{$smarty.const._CLOSE}>": function() {
									$(this).dialog("close");
									$(this).dialog("empty");
									return false;
								},
							Ok: function() {
								$.ajax({
									url: "<{$event_url}>submit.php",
									type: "POST",
									data: { event_id: event.id, op: "del"},
									dataType: "json",
									success: function(response) {
												if(response.status === "success") {
													$("div#cal_event").dialog("destroy");
													$('#calendar').fullCalendar('refetchEvents');
													$("#error_messages").text(response.message);

												} else if(response.status === "error") {
													$("#error_messages").text("<{$smarty.const._MD_EVENT_FAILURE}>: " + response.message);
													return false;
												} else {
													$("#error_messages").text("<{$smarty.const._MD_EVENT_FAILUREWENTWRONG}>: " + response.message);
													return false;
												}
									}
								});

								$(this).dialog( "close" );
								$(this).dialog("empty");

							}}
					});
					$("#event_alert").dialog("open");

				});

				$('#event_join').click(function(){
					var button = $(this);
					$.ajax({
						url: "<{$event_url}>submit.php",
						type: "POST",
						data: { event_id: event.id, op: "join"},
						dataType: "json",
						success: function(response) {
									if(response.status === "success") {
										//$("div#cal_event").dialog("destroy");
										$('#calendar').fullCalendar('refetchEvents');
										$("#event_joining").html("");

										$("#event_success").html(response.message);

									} else if(response.status === "error") {
										$("#event_success").html("<{$smarty.const._MD_EVENT_FAILURE}>: " + response.message);
										return false;
									} else {
										$("#event_success").html("<{$smarty.const._MD_EVENT_FAILUREWENTWRONG}>: " + response.message);
										return false;
									}
						}
					});
				});

				$('#event_unjoin').click(function(){
					var button = $(this);
					$.ajax({
						url: "<{$event_url}>submit.php",
						type: "POST",
						data: { event_id: event.id, op: "unjoin"},
						dataType: "json",
						success: function(response) {
									if(response.status === "success") {
										$('#calendar').fullCalendar('refetchEvents');
										$("#event_joining").html("");

										$("#event_success").html(response.message);

									} else if(response.status === "error") {
										$("#event_success").html("<{$smarty.const._MD_EVENT_FAILURE}>: " + response.message);
										return false;
									} else {
										$("#event_success").html("<{$smarty.const._MD_EVENT_FAILUREWENTWRONG}>: " + response.message);
										return false;
									}
						}
					});
				});

				<{if $can_comment}>
					/**
					 * comment functions
					 */
					$("#submit_comment").click(function(e, event){
						e.preventDefault();
						$("#event_comment_form").submit();
						return false;
					});
					$("#event_comment_form").unbind("submit").bind("submit", function(e) {
						e.preventDefault();
						e.stopPropagation();
						$.ajax({
							url: "<{$event_url}>submit.php",
							type: "POST",
							data: {op: "addcomment", comment_body: $("#event_comment_tarea").val(), event_id: $("div#cal_event").attr("data-id")},
							dataType: "json",
							success: function(response) {
								if(response.status === "success") {
									document.forms.event_comment_form.reset();
									$('#calendar').fullCalendar('refetchEvents');
									$("#event_success").html(response.message);
									$("#event_comment_container").html(response.comments);
									createToolTip();
								} else if(response.status == "error") {
									$("#event_success").html("<{$smarty.const._MD_EVENT_FAILURE}>: " + response.message);
								}
							}
						});
						return false;
					});
					$("body").delegate(".comment_approval_link", "click", function(e) {
						e.preventDefault();
						var link = $(this);
						$.ajax({
							url: "<{$event_url}>submit.php",
							type: "POST",
							dataType: "json",
							data: {event_id: $("div#cal_event").attr("data-id"), op: "approve_comment", comment_id: link.attr("data-id")},
							success: function(response) {
								if(response.status === "success") {
									$('#calendar').fullCalendar('refetchEvents');
									$("#event_success").html(response.message);
									$("#event_comment_container").html("");
									$("#event_comment_container").html(response.comments);
									createToolTip();
								} else if(response.status === "error") {
									$("#event_success").html("<{$smarty.const._MD_EVENT_FAILURE}>: " + response.message);
								}
							}
						});
					});
				<{/if}>
				var hash = window.location.hash;
				if(hash != "") {
					changeColorScheme("highlighted");
				}
				$('#event_edit').click(function(){
					var button = $(this);
					start = $.fullCalendar.formatDate( event.start, "yyyy/MM/dd HH:mm");
					end = $.fullCalendar.formatDate( event.end, "yyyy/MM/dd HH:mm");
					$("#event_startdate").val(start);
					$("#event_enddate").val(end);
					$("#event_id").val(event.id);
					$("#event_name").val(event.title);

					$("#event_allday").val(event.allDay);
					$("#event_cid").val(event.cid);
					$("#event_dsc_tarea").val(event.description);
					$("#event_contact").val(event.contact_name);
					$("#event_cemail").val(event.contact_mail);
					$("#event_phone").val(event.phone);
					$("#event_street").val(event.street);
					$("#event_city").val(event.city);
					$("#event_zip").val(event.zip);
					$("input:radio[name=event_public]:checked").val(event.event_public);
					$("#mid_event_url").val(event.url_mid);
					$("#caption_event_url").val(event.url_cap);
					$("#desc_event_url").val(event.url_dsc);
					$("#url_event_url").val(event.url_url);
					$("#target_event_url").val(event.url_tar);
					$("#event_joiners").val(event.event_joiners);
					$("#event_can_joint").val(event.event_can_joint);
					$("div#cal_event").dialog("close");
					$("#submit_form").dialog("open");
				});

				$('#event_clone').click(function(){
					var button = $(this);
					start = $.fullCalendar.formatDate( event.start, "yyyy/MM/dd HH:mm");
					end = $.fullCalendar.formatDate( event.end, "yyyy/MM/dd HH:mm");
					$("#event_startdate").val(start);
					$("#event_enddate").val(end);

					$("#event_id").val("0");
					$("#event_name").val(event.title);
					$("#event_allday").val(event.allDay);
					$("#event_cid").val(event.cid);
					$("#event_dsc_tarea").val(event.description);
					$("#event_contact").val(event.contact_name);
					$("#event_cemail").val(event.contact_mail);
					$("#event_phone").val(event.phone);
					$("#event_street").val(event.street);
					$("#event_city").val(event.city);
					$("#event_zip").val(event.zip);
					$("input:radio[name=event_public]:checked").val(event.event_public);
					$("#mid_event_url").val(event.url_mid);
					$("#caption_event_url").val(event.url_cap);
					$("#desc_event_url").val(event.url_dsc);
					$("#url_event_url").val(event.url_url);
					$("#target_event_url").val(event.url_tar);
					$("#event_joiners").val(event.event_joiners);
					$("#event_can_joint").val(event.event_can_joint);
					$("div#cal_event").dialog("close");
					$("#submit_form").dialog("open");
				});
			};

			function changeColorScheme(text){
				var hash = window.location.hash.slice(1);
				setTimeout(function(){$('#'+hash).addClass(text);},500);
				setTimeout(function(){$('#'+hash).removeClass(text);},5000);
				var hash = location.hash.replace('#','');
			};

			function createToolTip() {
				$(document).ready(function(){
						$(".comment_user").on("mouseover click", function() {
							$(this).qtip({
								content: {
									text: $(this).next('div.event_popup').html(),
									title: $(this).attr('original-title')
								},
								show: {
									ready: true,
									event: 'click mouseenter',
									solo: true
								},
								hide: 'unfocus mouseleave',
								style: {
									width:500,
									viewport: $(window),
									textAlign:'left',
									tip:'bottomLeft',
									classes: 'qtip-dark qtip-rounded qtip-shadow',
								},
								position:   {
									target: 'mouse',
									my:'bottomLeft',
									adjust: {
										x: 0,  y: -5
									}
								},
								events: {
						             render: function(event, api) {
						                 api.elements.target.click(function(e) {
						                     if (api.wasClicked) {
						                         api.hide();
						                         api.wasClicked = false;
						                     }
						                     else {
						                         api.wasClicked = !api.wasClicked;
						                     }
						                 });
						             },
						             hide: function(event, api) {
						                 if(api.wasClicked && event.originalEvent.type === 'mouseleave') {
						                     try{ event.preventDefault(); } catch(e) {}
						                 }
						                 else {
						                     api.wasClicked = false;
						                 }
						             }
						         }
							});
						});
					})
				};

	});

	$.widget("ui.dialog", $.extend({}, $.ui.dialog.prototype, {
	    _title: function(title) {
	        if (!this.options.title ) {
	            title.html("&#160;");
	        } else {
	            title.html(this.options.title);
	        }
	    }
	}));
</script>